<script setup>
import useUserInfoStore from '/src/stores/userInfo.js';
import {useTokenStore} from "@/stores/token.js";
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {editUserService} from "@/api/user.js";
import {UpdatePhoneService} from '@/api/user.js';

const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const userInfo = ref({});
const formRef = ref(null);

const getUserInfo = () => {
  // 从 store 获取用户信息
  const storeInfo = userInfoStore.userInfo;
  if (!storeInfo) {
    ElMessage.error('获取用户信息失败');
    return;
  }

  // 复制用户信息到本地状态
  userInfo.value = {
    userId: storeInfo.userId,
    fullName: storeInfo.fullName,
    phone: storeInfo.phone || '',
    createTime: storeInfo.createTime,
    updateTime: storeInfo.updateTime
  };

  // 格式化时间
  if (userInfo.value.createTime) {
    userInfo.value.createTime = userInfo.value.createTime.replace('T', ' ');
  }
  if (userInfo.value.updateTime) {
    userInfo.value.updateTime = userInfo.value.updateTime.replace('T', ' ');
  }
};
getUserInfo();

const userInfoUpdate = async () => {
  // 使用 formRef 引用来验证表单
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log(userInfo)
        const result = await UpdatePhoneService(userInfo.value);
        ElMessage({
          message: result.message ? result.message : '修改成功',
          type: 'success',
        });
        userInfoStore.setUserInfo(userInfo.value);
      } catch (error) {
        ElMessage.error('修改失败，请重试');
      }
    } else {
      ElMessage.error('手机号不符合格式，请重新输入');
    }
  });
};

const rules = {
  nickName: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {pattern: /^\S{2,10}$/, message: '昵称长度为2~10位', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机', trigger: 'blur'},
    {pattern: /^\d{11}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ]
};
</script>

<template>
  <el-card style="max-width: 800px">
    <span>基本资料</span>
    <br>
    <el-form ref="formRef" :model="userInfo" :rules="rules" label-width="100px">
      <!--      <el-form-item label="用户名">-->
      <!--        <el-input v-model="userInfo.name" disabled></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item label="用户名" prop="nickname">
        <el-input v-model="userInfo.fullName"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userInfo.phone"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="userInfoUpdate">提交修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
